
import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'package:fluttertoast/fluttertoast.dart';

import '../../Services/api_service.dart';
import '../../base/base_widget.dart';
import '../../common/logger.dart';
import '../../model/system_tree_content_model.dart';
import '../../model/system_tree_model.dart';
import '../web/web_page.dart';

class KnowledgeContentPage extends StatefulWidget {
  final SystemTreeData data;
  final int? selectedIndex;
  const KnowledgeContentPage({super.key, required this.data, this.selectedIndex = 0});

  @override
  State<StatefulWidget> createState() {
    return KnowledgeContentPageState();
  }
}

class KnowledgeContentPageState extends State<KnowledgeContentPage> with TickerProviderStateMixin {
  late SystemTreeData _systemTreeData;
  late TabController _tabController;
  late int _selectedIndex;
  @override
  void initState() {
    super.initState();
    _systemTreeData = widget.data;
    _selectedIndex = widget.selectedIndex ?? 0;
  }

  @override
  void dispose() {
    super.dispose();
    _tabController.dispose();
  }

  @override
  Widget build(BuildContext context) {
    Color themeColor = Theme.of(context).primaryColor;
    _tabController = TabController(length: _systemTreeData.children?.length ?? 0,
        initialIndex: _selectedIndex,
        vsync: this);
    return Scaffold(
      appBar: AppBar(
        backgroundColor: themeColor,
        iconTheme: const IconThemeData(color: Colors.white),
        title: Text(_systemTreeData.name ?? "", style: const TextStyle(color: Colors.white),),
        bottom: TabBar(
            indicatorColor: Colors.white,
            labelStyle:const TextStyle(fontSize: 16, fontWeight:FontWeight.w500, color: Colors.white),
            unselectedLabelStyle: const TextStyle(fontSize: 16, color: Colors.white60),
            controller: _tabController,
            isScrollable: true,
            tabs: _systemTreeData.children!.map((SystemTreeChild item) {
              return Tab(
                text: item.name,
              );
            }).toList()),
      ),
      body: TabBarView(
        controller: _tabController,
        children: _systemTreeData.children!.map((item) {
          return NewsList(id: item.id ?? 0);
        }).toList(),
      ),
    );
  }
}

//知识体系文章列表
// ignore: must_be_immutable
class NewsList extends BaseWidget {
  final int id;
  NewsList({super.key, required this.id});
  @override
  BaseWidgetState<BaseWidget> getState() {
    return _NewsListState();
  }
}

class _NewsListState extends BaseWidgetState<NewsList> {
  List<SystemTreeContentChild> _contentList = [];
  final ScrollController _scrollController = ScrollController(); //listview的控制器
  int _page = 0;

  @override
  void initState() {
    super.initState();
    setAppBarVisible(false);
    showLoading();
    getData();
    _scrollController.addListener(() {
      if (_scrollController.position.pixels ==
          _scrollController.position.maxScrollExtent) {
        _getMore();
      }
    });
  }

  Future<Null> getData() async {
    _page = 0;
    int cid = widget.id;
    ApiService().getSystemTreeContent(_page, cid, (SystemTreeContentModel systemTreeContentModel) {
      if (systemTreeContentModel.errorCode == 0) {
        int count = systemTreeContentModel.data?.datas?.length ?? 0;
        if (count> 0) {
          showContent();
          setState(() {
            _contentList = systemTreeContentModel.data?.datas ?? [];
          });
        } else {
          showEmpty();
        }
      } else {
        Fluttertoast.showToast(msg: systemTreeContentModel.errorMsg ?? "err");
      }
    } as Function,(DioError error) {
      showError();
    });
  }

  Future<Null> _getMore() async {
    _page++;
    int id = widget.id;

    ApiService().getSystemTreeContent(_page, id, (SystemTreeContentModel systemTreeContentModel) {
      if (systemTreeContentModel.errorCode == 0) {
        int count = systemTreeContentModel.data?.datas?.length ?? 0;
        if (count > 0) {
          showContent();
          setState(() {
            _contentList.addAll(systemTreeContentModel.data?.datas ?? []);
          });
        } else {
          Fluttertoast.showToast(msg: "没有更多数据了");
        }
      } else {
        Fluttertoast.showToast(msg: systemTreeContentModel.errorMsg ?? "err");
      }
    },(DioError error) {
      showError();
    });
  }

  Widget? _renderRowItem(BuildContext context, int index) {
    if (index < _contentList.length) {
      return InkWell(
        child: Container(
          child: _buildNewsRowItem(_contentList[index]),
        ),
        onTap: () {
          String url = _contentList[index].link ?? "";
          logger.d(url);
          Navigator.of(context).push(MaterialPageRoute(builder: (context) {
            return WebViewPage(
                title: _contentList[index].title ?? "", url: url);
          }));
        },
      );
    }
    return null;
  }

  //新闻列表单个item
  Widget _buildNewsRowItem(SystemTreeContentChild item) {
    return Container(
      color: Colors.white,
      padding: const EdgeInsets.all(16),
      child: Column(
        children: <Widget>[
          Container(
              padding: const EdgeInsets.fromLTRB(8, 8, 8, 8),
              child: Row(
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                children: <Widget>[
                  Text(
                    item.author ?? "",
                    style: const TextStyle(fontSize: 12, color: Colors.grey),
                  ),
                  Expanded(
                    child: Text(
                      item.niceDate ?? "",
                      style: const TextStyle(fontSize: 12, color: Colors.grey),
                      textAlign: TextAlign.right,
                    ),
                  ),
                ],
              )),
          Container(
              padding: const EdgeInsets.fromLTRB(8, 0, 8, 8),
              child: Row(
                children: <Widget>[
                  Expanded(
                      child: Text(
                        item.title ?? "",
                        style: const TextStyle(
                            fontSize: 16,
                            color: Color(0xFF3D4E5F),
                            fontWeight: FontWeight.bold),
                        textAlign: TextAlign.left,
                      ))
                ],
              )),
          Container(
              padding: const EdgeInsets.fromLTRB(8, 0, 8, 8),
              child: Row(
                children: <Widget>[
                  Text(
                    item.superChapterName ?? "",
                    style: const TextStyle(fontSize: 12, color: Colors.grey),
                  ),
                  Text(
                    "/${item.chapterName ?? ""}",
                    style: const TextStyle(fontSize: 12, color: Colors.grey),
                    textAlign: TextAlign.right,
                  ),
                ],
              )),
        ],
      ),
    );
  }

  @override
  AppBar getAppBar() {
    return AppBar(
      title: const Text("不显示"),
    );
  }

  @override
  Widget getContentWidget(BuildContext context) {
    return RefreshIndicator(
      onRefresh: getData,
      child: ListView.separated(
        physics: const AlwaysScrollableScrollPhysics(),
        itemBuilder: _renderRowItem,
        itemCount: _contentList.length + 1,
        controller: _scrollController,
        separatorBuilder: (BuildContext context, int index) {
          return Container(
            height: 0.5,
            color: Colors.black26,
          );
        },
      ),
    );
  }

  @override
  void onClickErrorWidget() {
    showLoading();
    getData();
  }
}
